﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Sitefinity.Web.UI.ControlDesign;
using System.Text;
using System.Net;
using System.IO;
using Facebook;
using Facebook.Web;
using Newtonsoft.Json;
using System.Collections;
using Sitefinity.Contrib.SocialWidgets.Shared;

namespace Sitefinity.Contrib.SocialWidgets.Facebook
{
    [ControlDesigner(typeof(FacebookImageRotatorWidgetDesigner)), PropertyEditorTitle("Facebook Image Rotator Widget")]
    public partial class FacebookImageRotatorWidget : System.Web.UI.UserControl
    {
        #region Constants
        const string FQL_GET_OWNER_ID = "SELECT page_id FROM page WHERE name='{0}'";
        const string FQL_ANY_ALBUM_FORMAT = "SELECT pid, src_big, caption FROM photo WHERE aid IN (SELECT aid FROM album WHERE owner = {0}) ORDER BY created DESC LIMIT {1}";
        const string FQL_SPECIFIC_ALBUM_FORMAT = "SELECT pid, src_big, caption FROM photo WHERE aid IN (SELECT aid FROM album WHERE owner = {0} AND name = '{1}') ORDER BY created DESC LIMIT {2}";
        #endregion

        public string PID { get; set; }
        public string AlbumName { get; set; }
        public int MaximumImages { get; set; }
        public int RotationTimerSeconds { get; set; }
        public int Height { get; set; }
        public int Width { get; set; }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            var sb = new StringBuilder();

            FacebookApp app = new FacebookApp();

            try
            {
                string fqlPhotos = string.IsNullOrEmpty(AlbumName) ?
                    string.Format(FQL_ANY_ALBUM_FORMAT, PID, MaximumImages) :
                    string.Format(FQL_SPECIFIC_ALBUM_FORMAT, PID, AlbumName, MaximumImages);

                string initialHref = string.Empty;
                string initialSrc = string.Empty;
                string initialAlt = string.Empty;

                object queryResult = app.Query(fqlPhotos);
                if (null != queryResult)
                {
                    List<object> photos = new List<object>();
                    foreach (JsonObject result in (JsonArray)queryResult)
                    {
                        object src = string.Empty;
                        object alt = string.Empty;
                        if (result.TryGetValue("src_big", out src))
                        {
                            // If we can't get the alt, that isn't a fatal situation.
                            result.TryGetValue("caption", out alt);

                            if (0 == photos.Count)
                            {
                                initialHref = src.ToString();
                                initialSrc = src.ToString();
                                initialAlt = alt.ToString();
                            }

                            photos.Add(new { src = src, alt = alt, href = src });
                        }
                    }

                    string prefix = string.Format("facebook_{0}_{1}", PID, string.IsNullOrEmpty(AlbumName) ? "AllPhotos" : HttpUtility.HtmlEncode(AlbumName));
                    ImageRotatorUtility imageRotatorUtility = new ImageRotatorUtility(prefix);
                    imageRotatorUtility.AddReferences(this.Page);

                    string script = imageRotatorUtility.GenerateScript(JsonConvert.SerializeObject(photos), RotationTimerSeconds * 1000);
                    Page.ClientScript.RegisterStartupScript(this.GetType(), prefix, script);

                    dynamic first = photos[0];
                    string html = imageRotatorUtility.GenerateHtml(Width, Height, initialHref, initialSrc, initialAlt);
                    sb.Append(html);
                }
            }
            catch
            {
                sb.Append("Facebook Image Query failed.");
            }

            ImageRotatorHtml.Text = sb.ToString();
        }        
    }
}